package level4.events
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.utils.Dictionary;
	
	import level4.helpers.DictionaryHelper;
	import level4.interfaces.IGameDispose;
	import level4.interfaces.dispose.IDisposable;

	public class GameDisposeEventDispatcher implements IEventDispatcher , IDisposable
	{
		private var dispatcher:EventDispatcher;
		
		//所有的监听器
		private var listenerDict:Dictionary = new Dictionary();
		private var listenerDictCapture:Dictionary = new Dictionary();
		
		public function GameDisposeEventDispatcher()
		{
			dispatcher = new EventDispatcher(this);
		}
		public function addEventListener(type:String,listener:Function,useCapture:Boolean=false,priority:int=0,useWeakReference:Boolean=false):void{
			dispatcher.addEventListener(type,listener,useCapture,priority,useWeakReference);
			
			//添加
			var dict:Dictionary = listenerDict;
			if(useCapture)
				dict = listenerDictCapture;
			dict[listener] = type;
			
		}
		
		public function dispatchEvent(evt:Event):Boolean{
			return dispatcher.dispatchEvent(evt);
		}
		
		public function hasEventListener(type:String):Boolean{
			return dispatcher.hasEventListener(type);
		}
		
		public function removeEventListener(type:String,listener:Function,useCapture:Boolean=false):void{
			dispatcher.removeEventListener(type,listener,useCapture);
			
			//清理
			var dict:Dictionary = listenerDict;
			if(useCapture)
				dict = listenerDictCapture;
			dict[listener] = null;
			delete dict[listener];
		}
		
		public function willTrigger(type:String):Boolean{
			return dispatcher.willTrigger(type);
		}
		
		/**
		 * 移除 已记录的所有的监听器,不过,闭包方式的监听还是无法移除
		 * 所以,添加监听时不要用闭包.
		 * */
		public function removeAllEventListeners():void{
			var k:*;
			for(k in listenerDict){
				removeEventListener(listenerDict[k],k);
			}
			for(k in listenerDictCapture)
				removeEventListener(listenerDictCapture[k],k);
		}
		/**
		 * 此对象,有没有listener这个方法的监听器?
		 * */
		public function hasThisListener(listener:Function,useCapture:Boolean=false):Boolean{
			var dict:Dictionary = listenerDict;
			if(useCapture)
				dict = listenerDictCapture;
			for(var k:* in dict){
				if(k == listener)
					return true;
			}
			return false;
		}
		/**
		 * 获取 监听器的数量
		 * */
		public function get listenerCount():int{
			var count:int = 0;
			for(var k:Object in listenerDict){
				count ++;
			}
			return count;
		}
		
		public function dispose():void{
			DictionaryHelper.removeAllKeys(listenerDict);
			DictionaryHelper.removeAllKeys(listenerDictCapture);
		}
	}
}